package controllers

import java.io.File
import java.nio.file.Files

import config.{Global, MyFile}
import javax.inject.{Inject, Singleton}
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents, Headers}

import scala.concurrent.ExecutionContext

class FruitController@Inject()(cc: ControllerComponents
                              )(implicit exec: ExecutionContext)
  extends AbstractController(cc)  with MyFile {

  def fruitPage = Action{implicit request=>
    Ok(views.html.fruit.fruitPage())
  }


  def getAllFruitImg = Action{implicit request=>
    val files = s"${Global.path}/fruits".listFile.map(_.getName)
    Ok(Json.toJson(files))
  }

  def getFruitImage(name: String) = Action { implicit request =>
    val path = s"${Global.path}/fruits/${name.replaceAll("\\\\", "").replaceAll("/", "")}".toFile
    SendImg(path, request.headers)
  }

  def SendImg(file: File, headers: Headers) = {
    val lastModifiedStr = file.lastModified().toString
    val MimeType = "image/jpg"
    val byteArray = Files.readAllBytes(file.toPath)
    val ifModifiedSinceStr = headers.get(IF_MODIFIED_SINCE)
    if (ifModifiedSinceStr.isDefined && ifModifiedSinceStr.get == lastModifiedStr) {
      NotModified
    } else {
      Ok(byteArray).as(MimeType).withHeaders(LAST_MODIFIED -> file.lastModified().toString)
    }
  }


}
